﻿#include "scroll_mode_thread.h"
#include <iostream>

void ScrollModeADCThread::start() {
  thread_is_running_ = true;
  
  auto base_device = base_device_.lock();
  if (!base_device) {
    return;
  }
  
  data_length_threshold_ = base_device->GetCurrentDataLength();
  batch_read_size_ = data_length_threshold_;
  data_.resize(base_device->GetADCLegalChannelSize());
  for (int i = 0; i < data_.size(); i++) {
    data_[i].reserve(2 * data_length_threshold_);
  }
  
  // 启动线程
  thread_ = std::thread(&ScrollModeADCThread::run, this);
}

void ScrollModeADCThread::quit() {
  {
    std::lock_guard<std::mutex> lock(mutex_);
    thread_is_running_ = false;
  }
  cv_.notify_one();
  
  if (thread_.joinable()) {
    thread_.join();
  }
}

void ScrollModeADCThread::run() {
  while (thread_is_running_) {
    int read_count = ReadADCData();
    
    if (read_count <= 0) {
      // 添加短暂休眠以避免CPU占用过高
      std::this_thread::sleep_for(std::chrono::microseconds(100));
      continue;
    }
    
    current_data_length_ += read_count;
    
    if (current_data_length_ >= data_length_threshold_) {
      current_data_length_ = 0;
      
      // 使用回调函数代替信号槽
      if (data_callback_) {
        data_callback_(data_);
      }
      
      for (auto &i: data_) {
        i.clear();
        i.reserve(2 * data_length_threshold_);
      }
    }
  }
}

int ScrollModeADCThread::ReadADCData() {
  auto base_device = base_device_.lock();
  if (!base_device) {
    return 0;
  }
  
  const auto channel_number = base_device->GetADCLegalChannelSize();
  int total_read_count = 0;
  
  // 为每个通道批量读取数据
  for (int i = 0; i < channel_number; i++) {
    auto temp_data = std::make_unique<float[]>(batch_read_size_);
    bool success = base_device->TryReadADCData(i, temp_data.get(), batch_read_size_);
    
    if (!success) {
      continue;
    }
    
    // 将批量读取的数据添加到对应通道的数据容器中
    for (uint32_t j = 0; j < batch_read_size_; j++) {
      data_[i].emplace_back(temp_data[j]);
    }
    
    total_read_count = batch_read_size_; // 所有通道应该读取相同数量的数据
  }
  
  return total_read_count;
}
